<template>
  <div>
    <div>
      <el-dialog title="添加用户" :visible.sync="$props.visible" width="50%" @close="handleClose">

        <div class="add-content">
          <el-form
            ref="formName"
            :model="staffFrom"
            :rules="staffRules"
            label-width="120px"
            style="margin-top: 10px;"
          >
            <el-form-item label="用户类型：" prop="type">
              <el-select v-model="staffFrom.type" filterable placeholder="请选择" style="width: 60%;" @change="handleUserTypeChange">
                <el-option
                  v-for="item in validUserTypesList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-if="staffFrom.type !== null" label="所属角色：" prop="roleIds">
              <el-select v-model="staffFrom.roleIds" filterable placeholder="请选择" style="width: 60%;">
                <el-option
                  v-for="item in validRolesList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手机：" prop="mobile">
              <el-input v-model="staffFrom.mobile" placeholder="请输入手机号" style="width: 60%;" />
            </el-form-item>
            <el-form-item label="姓名：" prop="name">
              <el-input v-model="staffFrom.name" placeholder="请输入姓名" style="width: 60%;" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input v-model="staffFrom.password" show-password placeholder="请输入密码" style="width: 60%;" />
            </el-form-item>
          </el-form>
        </div>

        <span class="dialog-footer">
          <div style="margin-top:15px;">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addUser, checkMobile } from '@/api/iam/iamUser'
import { validUserPhone } from '@/utils/validate'
import * as R from 'ramda'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userTypesMap: {
      type: Map,
      default: {}
    },
    userTypesList: {
      type: Array,
      default() {
        return []
      }
    },
    rolesList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (R.isNil(value) || R.isEmpty(value) || !validUserPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        checkMobile(value).then((response) => {
          if (response.isExist) {
            callback(new Error('手机号码已被注册，请换一个试试。'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      validUserTypesList: R.filter(x => x.canCreateFromHere, this.$props.userTypesList),
      staffFrom: {
        type: null,
        roleIds: [],
        mobile: '',
        name: '',
        password: ''
      },
      validRolesList: [],
      staffRules: {
        type: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择所属角色', trigger: 'blur' }],
        mobile: [{ required: true, message: '请填写手机号', trigger: 'blur' }, { validator: validateMobile }],
        name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        password: [{ required: true, message: '请填写密码', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.validRolesList = R.clone(this.rolesList)
  },
  methods: {
    // 弹出框关闭后触发
    handleClose() {
      // 子组件调用父组件方法，并传递参数
      this.$emit('handleClose')
    },
    handleSuccess() {
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      this.handleClose()
      this.$emit('handleSuccess')
    },
    handleUserTypeChange(userTypeId) {
      if (!R.isNil(userTypeId)) {
        const userType = this.userTypesMap.get(userTypeId)
        this.validRolesList = R.filter(x => x.accessLevel === userType.accessLevel, this.$props.rolesList)
      }
    },
    // 新增
    handleSubmit() {
      this.$refs['formName'].validate((valid) => {
        if (valid) {
          addUser(R.mergeLeft({ roleIds: R.split(',', this.staffFrom.roleIds) }, this.staffFrom)).then((response) => {
            this.handleSuccess()
          })
        }
      })
    }
  }
}
</script>
<style>
.add-content {
    border: 1px solid #e4e4e4;
    width: 90%;
    margin: 0 auto;
    height: 300px;
}
.dialog-footer{
    width: 97%;
    display: flex;
    justify-content:center;
}
</style>
